package xuegao.study.mall.admin.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 过滤器,用于从请求头中获取到tranceId,并写入到请求头
 */
public class ServletLogFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(ServletLogFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletReq = (HttpServletRequest) request;
        String uri = servletReq.getRequestURI();
        String TRACE_ID = "traceId";
        String traceId = servletReq.getHeader(TRACE_ID);
        if (!StringUtils.hasText(traceId)) {
            traceId = genTraceId();
        }
        MDC.put(TRACE_ID, traceId);
        logger.info("filter uri:{}", uri);
        chain.doFilter(request, response);
    }

    private String genTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
